#include "RenderTarget.h"

#include <ezlogger_headers.hpp>

namespace Crows3D
{
   RenderTarget::RenderTarget(void)
   {
   }

   RenderTarget::~RenderTarget(void)
   {
   }


   //
   bool RenderTarget::CreateRenderTarget(HINSTANCE hInstance, int nCmdShow, 
									     int width, int height, bool windowed)
   {
      DWORD style = 0;


      EZLOGGERSTREAM << "Creating Win32 Window with specified dimensions - width: " << width
                     << ", height: " << height << ", windowed: " << windowed << std::endl;

      // Register class
      WNDCLASSEX wcex;
      wcex.cbSize = sizeof(WNDCLASSEX);
      wcex.style = CS_HREDRAW | CS_VREDRAW;
      wcex.lpfnWndProc = WndProc;
      wcex.cbClsExtra = 0;
      wcex.cbWndExtra = 0;
      wcex.hInstance = hInstance;
      wcex.hIcon = LoadIcon( hInstance, (LPCTSTR)IDI_APPLICATION );
      wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
      wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
      wcex.lpszMenuName = NULL;
      wcex.lpszClassName = L"WindowClass";
      wcex.hIconSm = LoadIcon( wcex.hInstance, (LPCTSTR)IDI_APPLICATION );

      
      if( !RegisterClassEx(&wcex) )
      {
         EZLOGGERSTREAM << "ERROR: Couldn't register window class" << std::endl;
         return false;
      }

      // Figure out the style
      if (windowed)
      {
         style = WS_OVERLAPPEDWINDOW;
      }
      else
      {
         style = WS_POPUP;
      }

      // Create window
      this->hInstance = hInstance;
      RECT rc = { 0, 0, width, height };
      AdjustWindowRect( &rc, style, FALSE );

      hwnd = CreateWindowEx(NULL, L"WindowClass", L"Crows3D", 
                            style, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, 
                            rc.bottom - rc.top, NULL, NULL, hInstance, NULL );
      if( !hwnd )
      {
         EZLOGGERSTREAM << "ERROR: Couldn't create window" << std::endl;
         return false;
      }

      ShowWindow( hwnd, nCmdShow );

      return true;
   }


   LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
   {
      //EZLOGGERSTREAM << "Processing Windows messages" << std::endl;

      switch( message )
      {
         case WM_DESTROY:
            EZLOGGERSTREAM << "Window ordered to close, posting a quit message" << std::endl;

            PostQuitMessage(0);
            break;

         default:
            return DefWindowProc(hWnd, message, wParam, lParam);
      }

      return 0;
   }
}